package com.rongji.dfish.demo.editor.view;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.rongji.dfish.base.Utils;
import com.rongji.dfish.base.util.DateUtil;
import com.rongji.dfish.demo.constant.DemoConstants;
import com.rongji.dfish.demo.editor.service.EditorDirService;
import com.rongji.dfish.demo.editor.service.EditorService;
import com.rongji.dfish.demo.editor.service.uiadaptor.AdaptorManager;
import com.rongji.dfish.demo.entity.DfishView;
import com.rongji.dfish.demo.entity.DfishViewDir;
import com.rongji.dfish.demo.entity.DfishViewNode;
import com.rongji.dfish.demo.pub.view.PubView;
import com.rongji.dfish.framework.FrameworkHelper;
import com.rongji.dfish.ui.Command;
import com.rongji.dfish.ui.command.AjaxCommand;
import com.rongji.dfish.ui.command.ConfirmCommand;
import com.rongji.dfish.ui.command.JSCommand;
import com.rongji.dfish.ui.command.MenuCommand;
import com.rongji.dfish.ui.form.Checkbox;
import com.rongji.dfish.ui.form.Spinner;
import com.rongji.dfish.ui.form.Text;
import com.rongji.dfish.ui.form.Textarea;
import com.rongji.dfish.ui.helper.FormPanel;
import com.rongji.dfish.ui.helper.Label;
import com.rongji.dfish.ui.layout.AlbumLayout;
import com.rongji.dfish.ui.layout.ButtonBar;
import com.rongji.dfish.ui.layout.HorizontalLayout;
import com.rongji.dfish.ui.layout.VerticalLayout;
import com.rongji.dfish.ui.layout.View;
import com.rongji.dfish.ui.widget.Button;
import com.rongji.dfish.ui.widget.Html;
import com.rongji.dfish.ui.widget.Img;
import com.rongji.dfish.ui.widget.Leaf;
import com.rongji.dfish.ui.widget.Split;
import com.rongji.dfish.ui.widget.SubmitButton;
import com.rongji.dfish.ui.widget.TreePanel;

public class EditorDirView extends EditorCommonView {

	/**
	 * 
	 * @param targetDir
	 * @param dirMap
	 * @param subDirs
	 * @param subViews
	 * @param loginUser
	 * @param fromModule
	 * @return
	 */
	public static View buildIndexView(DfishViewDir targetDir,String viewId, Map<String, List<DfishViewDir>> dirMap, Map<String, List<DfishView>> viewMap, String fromModule) {
		// 模板案例模块
		boolean isTempMod = DemoConstants.MOD_EXAMPLE.equals(fromModule);
		
		if (targetDir == null) {
			String dirCreator = null;
			if (isTempMod) {
				dirCreator = DemoConstants.USER_ADMIN;
			} else {
				dirCreator = DemoConstants.USER_GUEST;
			}
			targetDir = getRootDir(dirCreator);
		}
		String targetDirId = targetDir.getDirId();
		
		String dirName = targetDir.getDirName();
		View view = buildMainView();
		
		view.setData("fromModule", fromModule);
		view.setData("targetDir", targetDir.getDirId());
		view.setData("dirCreator", targetDir.getDirCreator());
		
		// 分为左右结构
		TreePanel menu = (TreePanel) view.findNodeById(PubView.BODY_MENU);
		EditorDirView.fillMenu(menu, targetDir,viewId, dirMap, viewMap);
		
		
		if(Utils.isEmpty(viewId)){
			ButtonBar mainTitle = (ButtonBar) view.findNodeById(PubView.MAIN_TITLE);
			List<PathItem> pathItems = getDirItems(targetDir);
			fillPathBar(mainTitle, pathItems);
			
			// 主操作区
			ButtonBar mainOper = (ButtonBar) view.findNodeById(PubView.MAIN_OPER);
			// FIXME 状态区,目前用于全选操作区
			HorizontalLayout mainStatus = (HorizontalLayout) view.findNodeById(MAIN_STATUS);
			
			VerticalLayout mContent = (VerticalLayout) view.findNodeById(MAIN_CONTENT);
			// 主界面视图
			AlbumLayout mItems = new AlbumLayout("m_items").setHeight("*");
			mContent.add(mItems);
			mItems.setScroll(true).setFocusmultiple(true).setHeight("*");
			
			Img itemsPub = mItems.getPub();
			itemsPub.setFocusable(true).setCls("hand").setOn(Img.EVENT_CLICK, "editor.dir.enter(this,$itemId,$itemType);").setImgwidth(64).setImgheight(64).setTextwidth(100).setNobr(true);
			itemsPub.setOn(Img.EVENT_CONTEXTMENU, "editor.dir.itemMenu(this,$itemId,$itemType,$posIndex);");
			
			if (!isTempMod) {
				// 设置通用box属性
				itemsPub.setBox(new Checkbox("selItem", null, null, null, null).setOn(Checkbox.EVENT_CLICK, "editor.dir.checkItem(this);"));
				// 操作区补充相应按钮
				boolean isRootDir = EditorDirService.isRootDir(targetDir.getDirId());
				Button btnAdd = new Button("新建").setCls("btn btn-main").setOn("click", ";");
				mainOper.add(btnAdd);
				btnAdd.add(new Button("目录").setOn(Button.EVENT_CLICK, "editor.dir.edit(this,'','" + DemoConstants.ITEM_DIR + "');")); // editor.dir.edit(this, '', '0', '" + dirId + "');
				btnAdd.add(new Button("文件").setOn(Button.EVENT_CLICK, "editor.dir.edit(this,'','" + DemoConstants.ITEM_FILE + "');").setDisabled(isRootDir)); // editor.dir.edit(this, '', '1', '" + dirId + "');
				
				Button btnDel = new Button("删除").setId("btnDel").setDisabled(true);
				mainOper.add(btnDel);
				btnDel.setOn(Button.EVENT_CLICK, "editor.dir.delItem(this);");
				
				Button btnMore = new Button("更多");
				mainOper.add(btnMore);
				
				Button btnSort = new Button("排序方式");
				btnMore.add(btnSort);
				btnSort.add(new Button("名称").setOn(Button.EVENT_CLICK, "editor.dir.reorder(this,'" + targetDir.getDirId() + "','" + DemoConstants.ORDER_NAME + "');")); // this.cmd({type:'ajax', src:'editorDir/reSort/" + dirId + ";sortType=0'});
				btnSort.add(new Button("修改时间").setOn(Button.EVENT_CLICK, "editor.dir.reorder(this,'" + targetDir.getDirId() + "','" + DemoConstants.ORDER_TIME + "');")); // this.cmd({type:'ajax', src:'editorDir/reSort/" + dirId + ";sortType=1'});
				
				// 全选复选框
				mainStatus.add(new Checkbox("selAll", "全选", false, "1", "全选").setOn(Checkbox.EVENT_CLICK, "editor.dir.checkAllItem(this);"));
				
				mItems.setOn(AlbumLayout.EVENT_CONTEXTMENU, "editor.dir.dirMenu(this);");
			} else {
				view.findNodeById(PubView.MAIN_TOP).setHeight(50); // 没有全选那一栏,目前没有视图切换,高度设为50
				view.findNodeById(MAIN_STATUS).setHeight(0);
				view.findNodeById(MAIN_TOOL).setHeight(0);
				
			}
			
			mainOper.add(new Button("刷新").setOn(Button.EVENT_CLICK, "VM(this).relaod();"));
			// 放在左边菜单树,防止进入编辑器时被刷没
//			menu.addHidden("fromModule", fromModule);
//			menu.addHidden("targetDir", targetDir.getDirId());
//			menu.addHidden("dirCreator", targetDir.getDirCreator());
			
			mainStatus.addHidden("selectItem", "");
			
			List<DfishViewDir> subDirs = dirMap.get(targetDirId);
			List<DfishView> subViews = viewMap.get(targetDirId);
			fillFolderPanel(mItems, subDirs, subViews, !isTempMod);
			
			String timeStr = targetDir.getUpdateTime()==null? "[" + DemoConstants.VALUE_UNKNOWN + "]":DateUtil.format(targetDir.getUpdateTime());
			String pathStr = getPathStr(targetDir);
			
			VerticalLayout mRemark = (VerticalLayout) view.findNodeById(MAIN_REMARK);
			Html remark = new Html("", "<div id='folderinfo'>名称：" + dirName + "<br/>类型：目录<br/>位置：" + pathStr
					+ "<br/>包含：" + (subDirs == null ? 0 : subDirs.size()) + "个目录, " + (subViews == null ? 0 : subViews.size()) + "个文件<br/>时间：" + timeStr 
					+ "<br/>属性：" + (isTempMod ? "只读" : "可编辑")
					+ "<br/></div>");
			mRemark.add(remark);
	
		}else{
			EditorService editorService=FrameworkHelper.getBean(EditorService.class);
			List<DfishViewNode> viewNodes = editorService.findViewNodes(viewId);
			AdaptorManager.getInstance().getCompInfo().sortViewNodesByGroups(viewNodes);
			DfishView targetView=editorService.getView(viewId);
			
			List<DfishView> versions = editorService.findVersionViews(targetView.getViewOrigin(), EditorService.STATUS_VERSION);
			
			try {
				View fileView=EditorView.buildIndexView(targetView, targetDir, viewNodes, versions, fromModule) ;
				view.replaceNodeById(fileView.getNode());
				for(Map.Entry<String,Command<?>> entry:fileView.getCommands().entrySet()){
					view.addCommand(entry.getKey(), entry.getValue());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 这些命令共用
		//		view.addCommand("enterDir", PubView.getAjaxCommand("editorDir/enterDir?dirId=$0&fromModule=$1&reloadMenu=$2"));
		view.addCommand("move", PubView.getAjaxCommand("editorDir/move?itemId=$0&itemType=$1&moveType=$2"));
		view.addCommand("reorder", PubView.getAjaxCommand("editorDir/reorder?dirId=$0&orderType=$1"));
		view.addCommand("copyItem", PubView.getAjaxCommand("editorDir/copyItem?itemId=$0&itemType=$1&copyType=$2"));
		view.addCommand("pasteItem", PubView.getAjaxCommand("editorDir/pasteItem?toDir=$0"));
		//		view.addCommand("moveTo", PubView.getDialogCommand("moveTo", "std", "移动到..", PubView.DIALOG_SIZE_MEDIUM, "editorDir/moveTo?itemId=$0&itemType=$1&fromDir=$2"));
		//		view.addCommand("copyTo", PubView.getDialogCommand("copyTo", "std", "复制到..", PubView.DIALOG_SIZE_MEDIUM, "editorDir/copyTo?itemId=$0&itemType=$1&fromDir=$2"));
		view.addCommand("delete", new ConfirmCommand("确定要删除所选项？").setYes(PubView.getAjaxCommand("editorDir/delete?selectItem=$0&targetDir=$1")));
		view.addCommand("edit", PubView.getDialogCommand("edit", "std", "编辑", PubView.DIALOG_SIZE_MEDIUM, "editorDir/edit?editId=$0&editType=$1&targetDir=$2&fromModule=$3"));
		view.addCommand("dirMenu", new AjaxCommand("editorDir/dirMenu?targetDir=$0"));
		view.addCommand("itemMenu", new AjaxCommand("editorDir/itemMenu?itemId=$0&itemType=$1&posIndex=$2"));
		return view;
	}
	
	public static String getPathStr(DfishViewDir dir) {
		// FIXME 获取具体根目录
		StringBuilder pathStr = new StringBuilder();
		if (Utils.notEmpty(dir.getDirPath())) {
			EditorDirService editorDirService = FrameworkHelper.getBean(EditorDirService.class);
			List<String> dirs = Arrays.asList(dir.getDirPath().split("/"));
			Map<String, String> dirNames = editorDirService.findDirNamesBatch(dirs.toArray(new String[]{}));
			for (String item : dirs) {
				if (item.equals(dir.getDirId())) {
					continue;
				}
				pathStr.append('/');
				if (Utils.isEmpty(item)) {
					pathStr.append(getDirName(dir.getDirCreator()));
				} else {
					pathStr.append(dirNames.get(item));
				}
			}
		}
		return pathStr.toString();
	}

	private static void fillFolderPanel(AlbumLayout mainContent, List<DfishViewDir> subDirs, List<DfishView> subViews, boolean isEdit) {
		subDirs = subDirs == null ? new ArrayList<DfishViewDir>(0) : subDirs;
		subViews = subViews == null ? new ArrayList<DfishView>(0) : subViews;
		int dirSize = subDirs.size();
		// 位置;0:开头,-1结尾,其他:中间
		for (int i = 0; i < dirSize; i++) {
			DfishViewDir subDir = subDirs.get(i);
			int posIndex = i;
			if (posIndex == dirSize - 1) { // 最后一个位置设为-1
				posIndex = -1;
			}
			mainContent.add(buildDirWidget(subDir, posIndex, isEdit));
		}
		int viewSize = subViews.size();
		for (int i = 0; i < viewSize; i++) {
			DfishView subView = subViews.get(i);
			int posIndex = i;
			if (posIndex == dirSize - 1) { // 最后一个位置设为-1
				posIndex = -1;
			}
			mainContent.add(buildViewWidget(subView, posIndex, isEdit));
		}
	}

	/**
	 * FIXME 临时写的目录展示的方法
	 * 
	 * @param subDir
	 * @return
	 */
	private static Img buildDirWidget(DfishViewDir subDir, int posIndex, boolean editable) {
		Img img = new Img("m/demo/img/folder.png");
		// 考虑在pub中加
		img.setText(subDir.getDirName()).setData("itemId", subDir.getDirId()).setData("itemType", DemoConstants.ITEM_DIR).setData("posIndex", posIndex);
		if (editable) {
			img.setBox(new Checkbox(null, null, null, DemoConstants.ITEM_DIR + subDir.getDirId(), null));
		}
		return img;
	}

	/**
	 * FIXME 临时写的视图展示的方法
	 * 
	 * @param subView
	 * @return
	 */
	private static Img buildViewWidget(DfishView subView, int posIndex, boolean editable) {
		Img img = new Img("m/demo/img/file.png");
		img.setText(subView.getViewName()).setData("itemId", subView.getViewId()).setData("itemType", DemoConstants.ITEM_FILE).setData("posIndex", posIndex);
		if (editable) {
			img.setBox(new Checkbox(null, null, null, DemoConstants.ITEM_FILE + subView.getViewId(), null));
		}

		return img;
	}
	
	public static MenuCommand buildItemMenu(String itemId, String itemType, int posIndex, String fromModule) {
		MenuCommand menu = new MenuCommand();
//		String enterCmd = isEditor ? "editor.dir.enterEditor(this,'" + itemId + "');" : "editor.dir.enterDir(this, '" + itemId + "', '" + category + "');";
		String enterCmd = "editor.dir.enter(this, '" + itemId + "', '" + itemType + "');";
		
		boolean isMultiple = false;
		menu.add(new Button("打开").setOn(Button.EVENT_CLICK, enterCmd).setDisabled(isMultiple));
		menu.add(new Split());
		
		// 仅支持文件的复制,目录的复制比较复杂,暂不考虑
//		menu.add(new Button("复制到..").setOn(Button.EVENT_CLICK, "VM(this).cmd('copyTo','" + itemId + "','" + itemType + "',VM(this).data('targetDir'));").setDisabled(!isEditor));
		
		boolean fromTempMod = DemoConstants.MOD_EXAMPLE.equals(fromModule);
		
		boolean isFile = DemoConstants.ITEM_FILE.equals(itemType);
		if (!fromTempMod) {
			menu.add(new Button("剪切").setOn(Button.EVENT_CLICK, "this.cmd('copyItem','" + itemId + "','" + itemType + "','" + DemoConstants.OPER_CUT + "');"));
		}
		
		menu.add(new Button("复制").setOn(Button.EVENT_CLICK, "this.cmd('copyItem','" + itemId + "','" + itemType + "','" + DemoConstants.OPER_COPY + "');").setDisabled(!isFile));
		if (!fromTempMod) {
			menu.add(new Button("粘贴").setOn(Button.EVENT_CLICK, "this.cmd('pasteItem','" + itemId + "');").setDisabled(isFile));
			
			Button btnMove = new Button("位置");
			menu.add(btnMove);
			boolean isFirst = posIndex == 0;
			boolean isLast = posIndex < 0;
			btnMove.add(new Button("置顶").setOn(Button.EVENT_CLICK, "VM(this).cmd('move','" + itemId + "','" + itemType + "','" + DemoConstants.MOVE_TOP + "');").setDisabled(isMultiple || isFirst));
			btnMove.add(new Button("上移").setOn(Button.EVENT_CLICK, "VM(this).cmd('move','" + itemId + "','" + itemType + "','" + DemoConstants.MOVE_UP + "');").setDisabled(isMultiple || isFirst));
			btnMove.add(new Button("下移").setOn(Button.EVENT_CLICK, "VM(this).cmd('move','" + itemId + "','" + itemType + "','" + DemoConstants.MOVE_DOWN + "');").setDisabled(isMultiple || isLast));
			btnMove.add(new Button("置底").setOn(Button.EVENT_CLICK, "VM(this).cmd('move','" + itemId + "','" + itemType + "','" + DemoConstants.MOVE_BOTTOM + "');").setDisabled(isMultiple || isLast));
			
			menu.add(new Split());
			menu.add(new Button("删除").setOn(Button.EVENT_CLICK, "VM(this).cmd('delete','" + itemType + itemId  + "',VM(this).data('targetDir'));"));
		}
		
		
		menu.add(new Split());
		menu.add(new Button("属性").setOn(Button.EVENT_CLICK, "editor.dir.edit(this, '" + itemId + "', '" + itemType + "');").setDisabled(isMultiple));
		return menu;
	}
	
	public static MenuCommand buildDirMenu(String targetDir, boolean hasCopied) {
		
		boolean isRootDir = EditorDirService.isRootDir(targetDir);
		MenuCommand menu = new MenuCommand();
		Button btnAdd = new Button("新建");
		menu.add(btnAdd);
		btnAdd.add(new Button("目录").setOn(Button.EVENT_CLICK, "editor.dir.edit(this, '', '" + DemoConstants.ITEM_DIR + "');"));
		btnAdd.add(new Button("文件").setOn(Button.EVENT_CLICK, "editor.dir.edit(this, '', '" + DemoConstants.ITEM_FILE + "');").setDisabled(isRootDir));
		menu.add(new Split());
		
		menu.add(new Button("粘贴").setOn(Button.EVENT_CLICK, "this.cmd('pasteItem','" + targetDir + "');").setDisabled(!hasCopied));
		
		Button btnOrder = new Button("排序方式");
		menu.add(btnOrder);
		btnOrder.add(new Button("名称").setOn(Button.EVENT_CLICK, "editor.dir.reorder(this,'" + targetDir + "','" + DemoConstants.ORDER_NAME + "');"));
		btnOrder.add(new Button("修改时间").setOn(Button.EVENT_CLICK, "editor.dir.reorder(this,'" + targetDir + "','" + DemoConstants.ORDER_TIME + "');"));
		
		
		menu.add(new Split());
		menu.add(new Button("属性").setOn(Button.EVENT_CLICK, "editor.dir.edit(this, '" + targetDir + "', '" + DemoConstants.ITEM_DIR + "');"));
		
		return menu;
	}

	/**
	 * 当前文件的编辑
	 * 
	 * @param dView
	 *            当前文件的信息
	 * @param isCopy
	 * @return
	 */
	public static View buildViewEditView(DfishView dView, boolean readonly) {
		View view = PubView.buildDialogView();

		FormPanel main = (FormPanel) view.findNodeById(PubView.DIALOG_MAIN);

		if (dView == null) {
			// 这个理论上不会出现,容错处理
			dView = new DfishView();
		}
		
		main.addHidden("viewId", dView.getViewId());
		main.addHidden("viewVersion", String.valueOf(dView.getViewVersion()));
//		main.addHidden("isCopy", isCopy ? "1" : "0");
		main.add(new Text("viewName", "名称", dView.getViewName()).setRequired(true).setReadonly(readonly));
		main.addHidden("viewCreator", dView.getViewCreator());
//		main.add(new Text("viewCreator", "创建人", dView.getViewCreator()));
		main.add(new Textarea("viewRemark", "备注", dView.getViewRemark()).setReadonly(readonly));
		main.add(new Spinner("viewOrder", "排序", dView.getViewOrder(), 10, 99999999, 10).setReadonly(readonly));
//		if (isCopy) {
//			main.add(new Hidden("oldViewId", dView.getViewId()));
//			main.add(new Hidden("fromDir", dView.getViewDir()));
//			main.add(new Combobox("viewDir", "选择目录", dView.getViewDir(), "editorDir/dirCandidate?dirId=$value").setSuggest(true).setRequired(true)
//					.setPicker(PubView.getDialogCommand("copySelect", "std", "选择目录", PubView.DIALOG_SIZE_MEDIUM, "editorDir/copySelect?fromDir=$value").setCover(true)));
//		} else {
			main.addHidden("viewDir", dView.getViewDir());
//		}
		main.add(new Label("创建时间", DateUtil.format(dView.getCreateTime())));
		main.add(new Label("修改时间", DateUtil.format(dView.getUpdateTime())));

		if (!readonly) {
			ButtonBar btn = (ButtonBar) view.findNodeById(PubView.DIALOG_BTN);
			
			btn.add(0, new SubmitButton("确定").setCls("btn btn-submit").setOn(SubmitButton.EVENT_CLICK, "this.cmd('save');"));
			view.addCommand("save", PubView.getSubmitCommand("editorDir/saveView"));
		}

//		if (isCopy) {
//			view.addCommand("save", PubView.getSubmitCommand("editorDir/doCopy"));
//		} else {
//		}

		return view;
	}

	/**
	 * 文件目录编辑
	 * 
	 * @param viewDir
	 *            当前文件的视图目录
	 * @return
	 */
	public static View buildDirEditView(DfishViewDir viewDir, boolean readonly) {
		View view = PubView.buildDialogView();

		FormPanel main = (FormPanel) view.findNodeById(PubView.DIALOG_MAIN);

		if (viewDir == null) {
			// 理论上目录不可能为空
			viewDir = new DfishViewDir();
		}
		main.addHidden("dirId", viewDir.getDirId());
		main.addHidden("dirParent", viewDir.getDirParent());
		main.addHidden("dirCreator", viewDir.getDirCreator());
		main.add(new Text("dirName", "目录名称", viewDir.getDirName()).setRequired(true).setReadonly(readonly));
		main.add(new Label("类型", "目录"));
//		form.add(new Text("dirParentLabel", "位置", "视图" + editorDirService.getViewDirPath(viewDir.getDirPath()))
//		        .setReadonly(true));
		// form.add(new Combobox("dirParent", "上级目录", viewDir.getDirParent(),
		// ""));
		main.add(new Label("修改时间", DateUtil.format(viewDir.getUpdateTime())));
		main.add(new Text("dirNature", "属性", "可编辑").setReadonly(true));
		main.add(new Spinner("dirOrder", "目录排序", viewDir.getDirOrder(), 10, 99999999, 10).setReadonly(readonly));

		// ButtonBar btn = new ButtonBar("btn");
		// root.add(btn, "50");
		// btn.setAlign(ButtonBar.ALIGN_RIGHT);
		// btn.setStyle("background-color:#EEE; text-align:right;");

		if (!readonly) {
			ButtonBar btnBar = (ButtonBar) view.findNodeById(PubView.DIALOG_BTN);
			btnBar.add(0, new SubmitButton("确定").setCls("btn btn-submit").setOn(SubmitButton.EVENT_CLICK, "this.cmd('save');"));
			view.addCommand("save", PubView.getSubmitCommand("editorDir/saveDir"));
		}

		return view;
	}

	/**
	 * 移动功能的弹窗视图
	 * 
	 * @param dirList
	 * @param itemId
	 * @param itemType
	 * @param pDir
	 * @return
	 * @throws Exception
	 */
	public static View buildMoveToView(List<DfishViewDir> dirList, String itemId, String itemType, DfishViewDir pDir)
	        throws Exception {
		
//		TreePanel main = new TreePanel(PubView.DIALOG_MAIN);
//		View view = PubView.buildDialogView(main);
//
////		main.setPub(new Leaf().setOn(Leaf.EVENT_CLICK, "if(this.x.data.disabled=='1' ){"
////		        + "VM(this).f('targetDir').val('');" + "$.alert('此目录不可选择');}" + "else if((('"
////		        + DemoConstants.TYPE_EDITOR + "')==(VM(this).f('type').val()))" + "&&(this.x.data.dirId=='"
////		        + DemoConstants.ID_ROOT + "')) {" + "$.alert('此目录不可选择'); }"
////		        + "else{VM(this).f('targetDir').val(this.x.data.dirId);" + "}"));
//		main.addCls("bd-dlg-split").setStyle("margin:10px;").setHmin(22).setWmin(22);
//		main.addHidden("itemId", itemId);
//		main.addHidden("itemType", itemType);
//		main.addHidden("fromDir", pDir.getDirId());
//		main.addHidden("toDir", "");
//		
//		main.setFormat("javascript:return editor.dir.dirFormat($id,$text,$dis);");
//		main.setPub(new Leaf().setOn(Leaf.EVENT_CLICK, "editor.dir.selDir(this);").setIcon(".ico-folder").setOpenicon(".ico-folder-open"));
//		
//
//		Map<String, List<DfishViewDir>> dirMap = new HashMap<String, List<DfishViewDir>>();
//		String rootDirId = DemoConstants.DIR_PRE_USER + pDir.getDirCreator();
//		for (DfishViewDir dir : dirList) {
//			// FIXME 父目录不存在或错乱的情况暂不处理
//			String dirParent = dir.getDirParent();
//			if (DemoConstants.ID_ROOT.equals(dirParent)) {
//				dirParent = rootDirId;
//			}
//			List<DfishViewDir> tempList = dirMap.get(dirParent);
//			if (tempList == null) {
//				tempList = new ArrayList<DfishViewDir>();
//				dirMap.put(dirParent, tempList);
//			}
//			tempList.add(dir);
//		}
//
//		Set<String> disabledDirs = new HashSet<String>();
//		disabledDirs.add(pDir.getDirId());
//		if (DemoConstants.TYPE_DIR.equals(itemType)) {
//			fillDisabledDir(disabledDirs, itemId, dirMap);
//		} else {
//			disabledDirs.add(rootDirId);
//		}
//
//		DfishViewDir rootDir = buildRootDir(pDir.getDirCreator());
//
//		Leaf rootItem = parseTreeItem(rootDir, disabledDirs);
//		main.add(rootItem);
//		fillSubItem(rootItem, dirMap, disabledDirs);
//
//		ButtonBar btnBar = (ButtonBar) view.findNodeById(PubView.DIALOG_BTN);
//		btnBar.add(0, new SubmitButton("确定").setId("btnSave").setCls("btn btn-main").setOn(Button.EVENT_CLICK, "this.cmd('save');"));
//		// if(VM(this).f('targetDir').val()) {" + "this.cmd('move2NewDir');" +
//		// "$.dialog(this).close();" +
//        // "}else{$.alert('请选择目录');}
		
		View view = buildDirSelectView(dirList, itemId, itemType, pDir);
		view.addCommand("save", PubView.getSubmitCommand("editorDir/doMove"));
		return view;
	}
	
	public static View buildDirSelectView(List<DfishViewDir> dirList, String itemId, String itemType, DfishViewDir pDir) {
		TreePanel main = new TreePanel(PubView.DIALOG_MAIN);
		View view = PubView.buildDialogView(main);

		main.addCls("bd-dlg-split").setStyle("margin:10px;").setHmin(22).setWmin(22);
		main.addHidden("itemId", itemId);
		main.addHidden("itemType", itemType);
		main.addHidden("fromDir", pDir.getDirId());
		main.addHidden("toDir", "");
		
		main.setFormat("javascript:return editor.dir.dirFormat($id,$text,$dis);");
		main.setPub(new Leaf().setOn(Leaf.EVENT_CLICK, "editor.dir.selDir(this);").setIcon(".ico-folder").setOpenicon(".ico-folder-open"));
		

		Map<String, List<DfishViewDir>> dirMap = new HashMap<String, List<DfishViewDir>>();
		// 根用户
		Set<String> rootCreators = new HashSet<String>();
//		String rootDirId = DemoConstants.DIR_PRE_USER + pDir.getDirCreator();
		for (DfishViewDir dir : dirList) {
			rootCreators.add(dir.getDirCreator());
			// FIXME 父目录不存在或错乱的情况暂不处理
			String dirParent = dir.getDirParent();
			if (DemoConstants.ID_ROOT.equals(dirParent)) {
				dirParent = DemoConstants.ITEM_USER + dir.getDirCreator();
			}
			List<DfishViewDir> tempList = dirMap.get(dirParent);
			if (tempList == null) {
				tempList = new ArrayList<DfishViewDir>();
				dirMap.put(dirParent, tempList);
			}
			tempList.add(dir);
		}

		Set<String> disabledDirs = new HashSet<String>();
		disabledDirs.add(pDir.getDirId());
		if (DemoConstants.ITEM_DIR.equals(itemType)) {
			fillDisabledDir(disabledDirs, itemId, dirMap);
		} else {
			for (String creator : rootCreators) {
				disabledDirs.add(DemoConstants.ITEM_USER + creator);
			}
		}

		List<String> rootUsers = new ArrayList<String>(rootCreators);
		for (String creator : rootUsers) {
			DfishViewDir rootDir = getRootDir(creator);
			Leaf rootItem = parseTreeItem(rootDir, disabledDirs);
			main.add(rootItem);
			fillSubItem(rootItem, dirMap, disabledDirs);
		}
		

		ButtonBar btnBar = (ButtonBar) view.findNodeById(PubView.DIALOG_BTN);
		btnBar.add(0, new SubmitButton("确定").setDisabled(true).setId("btnSave").setCls("btn btn-main").setOn(Button.EVENT_CLICK, "this.cmd('save');"));
		
		return view;
	}
	
	/**
	 * 移动功能的弹窗视图
	 * 
	 * @param dirList
	 * @param itemId
	 * @param itemType
	 * @param pDir
	 * @return
	 * @throws Exception
	 */
	public static View buildCopySelectView(List<DfishViewDir> dirList, String itemId, String itemType, DfishViewDir pDir)
	        throws Exception {
		View view = buildDirSelectView(dirList, itemId, itemType, pDir);

		view.addCommand("save", new JSCommand("var d=$.dialog(this);d.commander.val(VM(this).fv('toDir'));d.close();"));
		return view;
	}

	private static void fillDisabledDir(Set<String> disabledDirs, String dirId, Map<String, List<DfishViewDir>> dirMap) {
		disabledDirs.add(dirId);
		List<DfishViewDir> subDirs = dirMap.get(dirId);
		if (subDirs != null) {
			for (DfishViewDir dir : subDirs) {
				fillDisabledDir(disabledDirs, dir.getDirId(), dirMap);
			}
		}
	}

	private static void fillSubItem(Leaf item, Map<String, List<DfishViewDir>> dirMap, Set<String> disabledDirs) {
		if (item == null) {
			return;
		}
		List<DfishViewDir> subDirs = dirMap.get(item.getId());
		if (subDirs != null) {
			for (DfishViewDir dir : subDirs) {
				Leaf subItem = parseTreeItem(dir, disabledDirs);
				item.add(subItem);
				fillSubItem(subItem, dirMap, disabledDirs);
			}
		}
	}

	private static Leaf parseTreeItem(DfishViewDir dir, Set<String> disabledDirs) {
		Leaf item = new Leaf();
		item.setId(dir.getDirId());
		item.setText(dir.getDirName());
		item.setOpen(true);
		if (disabledDirs.contains(dir.getDirId())) {
			item.setData("dis", "1");
		}
		return item;
	}

	/**
	 * 填充导航菜单
	 * @param tree 导航菜单节点
	 * @param dirMap 路径目录集
	 * @param targetDir 当前目录
	 */
	public static void fillMenu(TreePanel tree, DfishViewDir targetDir,String viewId, Map<String, List<DfishViewDir>> dirMap, Map<String, List<DfishView>> viewMap) {
		tree.getPub().setIcon(".ico-folder").setOpenicon(".ico-folder-open")
				.setOn(Leaf.EVENT_CONTEXTMENU, "this.focus(); var type=this.data('itemType');"
						+ "if(type=='D'){VM(this).cmd('dirMenu',this.data('targetDir'));}"
						+ "else if(type=='F'){var id=this.data('itemId');var index=this.data('posIndex');VM(this).cmd('itemMenu',id,type,index);}")
		        .setOn(TreePanel.EVENT_CLICK, "editor.dir.enter(this,$id,$itemType);").setTip(true);
		
//		Leaf root = new Leaf().setId("ROOT").setText("0".equals(category) ? "视图" : "模板").setIcon(".ico-folder-open");
//		tree.add(root);
//		root.setSrc("editorDir/open/ROOT_" + category);
//		// root.setSrc("VM.find('editorDir/open/ROOT_'+'"+category+"').reloadForAdd()");
//		root.setOn(Leaf.EVENT_CLICK, "editor.dir.enterDir(this, '" + DemoConstants.ID_ROOT + "', '" + category + "');");
//
//		root.setOpen(true);
		// FIXME 目前全部加载,前端展现的性能可能撑不住,后面需要改造成局部加载
		List<DfishViewDir> rootDirs = dirMap.get(DemoConstants.TREE_ROOT);
		if (Utils.notEmpty(rootDirs)) {
			for (DfishViewDir item : rootDirs) {
				Leaf leaf = new Leaf(item.getDirId(), item.getDirName()).setData("itemType", DemoConstants.ITEM_USER).setOpen(true);
				tree.add(leaf);
				fillNav(leaf, targetDir,viewId, dirMap, viewMap);
			}
		}
	}
	
	private static void fillNav(Leaf leaf, DfishViewDir targetDir,String viewId, Map<String, List<DfishViewDir>> dirMap, Map<String, List<DfishView>> viewMap) {
		if (leaf == null) {
			return;
		}
		String pDirId = leaf.getId();
		List<DfishViewDir> subDirs = dirMap.get(pDirId);
		if (Utils.notEmpty(subDirs)) {
			// FIXME 后面需要做动态加载
			String targetDirPath = targetDir.getDirPath();
			for (DfishViewDir dir : subDirs) {
				Leaf subLeaf = new Leaf(dir.getDirId(), dir.getDirName()).setData("itemType", DemoConstants.ITEM_DIR).setData("targetDir", dir.getDirId());
				leaf.add(subLeaf);
				String dirPath = dir.getDirPath();
				if (Utils.notEmpty(targetDirPath) && targetDirPath.startsWith(dirPath)) {
					subLeaf.setOpen(true);
					if (targetDirPath.equals(dirPath)) {
						subLeaf.setFocus(true);
					}
				}
//				if (Utils.isEmpty(dirPath) || !targetPath.equals(dirPath) && targetPath.startsWith(dirPath)) {
//					fillNav(subLeaf, pathDirs, targetDir);
//				}
				if (Utils.notEmpty(dirMap.get(dir.getDirId())) || Utils.notEmpty(viewMap.get(dir.getDirId()))) { // 有子目录或者视图时需级联下级
					fillNav(subLeaf, targetDir,viewId, dirMap, viewMap);
//					subLeaf.setSrc("editorDir/open/$id");
				}
			}
		}
		List<DfishView> subViews = viewMap.get(pDirId);
		if (Utils.notEmpty(subViews)) {
			int i = 0;
			for (DfishView dView : subViews) {
				boolean focus=dView.getViewId().equals(viewId);
				leaf.add(new Leaf(dView.getViewId(), dView.getViewName())
						.setIcon(".ico-file")
						.setData("itemId", dView.getViewId())
						.setData("itemType", DemoConstants.ITEM_FILE)
						.setData("posIndex", i++)
						.setFocus(focus?true:null));
			}
		}
	}

}
